package com.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.sql.SqlExecutor;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.setting.Setting;
import com.bean.WeiXinUser;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

@Service
public class UserService {

    private Log logger = LogFactory.get();


    /**
     * 根据企业微信用户查询人力资源系统是否存在
     * 若存在返回true,返回登陆成功页面
     * 若不存在返回false,执行账号同步操作
     * @param user
     * @return
     */
    public boolean getGzcssAccount(WeiXinUser user) {
        String userName = user.getName();
        String userMobile = user.getMobile();
        Setting setting = new Setting("config/db.setting");
        DSFactory df = DSFactory.create(setting);
        DataSource ds = df.getDataSource();
        Connection conn = null;

        try {

            conn = ds.getConnection();
            String TABLE_NAME = "gzcss_account";
            PreparedStatement ps = conn.prepareStatement("select * from " + TABLE_NAME + " where user_name = ? and mobile = ?");
            /* 执行查询语句，返回实体列表，一个Entity对象表示一行的数据，Entity对象是一个继承自HashMap的对象，存储的key为字段名，value为字段值 */
            List<Entity> entityList =  SqlExecutor.query(ps,new EntityListHandler(),new Object[] { userName,userMobile});
            logger.info("{}", entityList);

            if(entityList.size() > 0) return true;

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DbUtil.close(conn);
        }
        return false;
    }


    /**
     * 企业微信和人力资源系统账号同步操作
     * @param user
     */
    public int syncWeiXinGzcssAccount(WeiXinUser user)  {
        int intResult = 0;
        try {
            Long result = Db.use().insertForGeneratedKey(
                    Entity.create("gzcss_account")
                            .set("c_id", IdUtil.simpleUUID())
                            .set("user_name", user.getName())
                            .set("mobile", user.getMobile())
                            .set("mail", user.getEmail())
                            .set("job",user.getPosition())
                            .set("sex",user.getGender())
            );

            intResult = result.intValue();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return intResult;
    }

}
